package cn.yusei.teamTribe.service.relation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.yusei.teamTribe.dao.relation.RelationRequestDAO;
import cn.yusei.teamTribe.dao.relation.po.RelationRequestPO;
import cn.yusei.teamTribe.exception.AccessFailureException;
import cn.yusei.teamTribe.exception.RelationRequestNotExistsException;
import cn.yusei.teamTribe.exception.RepeatUpdateException;

@Service
public class RelationRequestService {

	@Autowired
	private RelationRequestDAO relationRequestDAO;
	
	/**
	 * 返回新插入的请求的 id
	 * @param id1
	 * @param id2
	 * @return
	 */
	public long sendRequest(int id1, int id2, String requestReason)
	{
		//TODO 判断是不是已经是好友
		if(relationRequestDAO.exists(id1, id2) == null)
		{
			RelationRequestPO relationRequest = new RelationRequestPO();
			relationRequest.setId1(id1);
			relationRequest.setId2(id2);
			relationRequest.setRequestReason(requestReason);
			relationRequestDAO.insert(relationRequest);
		}
		return relationRequestDAO.selectMaxId(id1, id2);
	}
	
	/**
	 * 返回指定 requestId 的好友请求
	 * @param requestId
	 * @return
	 */
	public RelationRequestPO getRequest(long requestId) throws RelationRequestNotExistsException
	{
		RelationRequestPO relationRequest = relationRequestDAO.selectById(requestId);
		if(relationRequest == null)
			throw new RelationRequestNotExistsException("好友申请 id：" + requestId + " 不存在");
		return relationRequest;
	}
	
	/**
	 * 返回发出请求的用户的 id
	 * 
	 * @param id
	 * @param requestId
	 * @param result
	 * @param responseReason
	 * @return
	 */
	public int sendResponse(int id, int requestId, int result, String responseReason) throws RepeatUpdateException, AccessFailureException
	{
		RelationRequestPO relationRequest = relationRequestDAO.selectById(requestId);
		if(relationRequest == null || relationRequest.getResult() != 0)
			throw new RepeatUpdateException("只能对好友请求 [" + requestId + "] 进行一次更新操作");
		if(relationRequest.getId2() != id)
			throw new AccessFailureException("用户 [" + id + "] 没有权限修改好友请求 [" + requestId + "]");
		relationRequest.setResult(result);
		if(result == 2)        //如果是拒绝
			relationRequest.setResponseReason(responseReason);
		relationRequestDAO.update(relationRequest);
		return relationRequest.getId1();
	}
	
}
